<template>
  <div class="user_wrapper">
    <el-space fill style="width: 100%">
      <el-card>
        <el-row>
          <el-col :span="6">
            <el-form :inline="true">
              <el-form-item label="角色名称">
                <el-input v-model="keyword" placeholder="请输入角色" />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="18" style="text-align: right">
            <el-space style="margin-bottom: 20px">
              <el-button type="primary" @click="searchUser">搜索</el-button>
              <el-button type="default" @click="resetSearch">重置</el-button>
            </el-space>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="spu_card_table common_card_wrapper">
        <el-space style="margin-bottom: 20px">
          <el-button type="primary" icon="plus" @click="addUser">
            添加
          </el-button>
        </el-space>

        <el-table
          :data="tableData"
          :border="true"
          v-loading="loading"
          element-loading-text="加载中..."
          height="650px"
        >
          <el-table-column type="index" label="#" width="100" align="center" />
          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="updateTime" label="更新时间" />
          <el-table-column prop="action" label="操作" width="320">
            <template #default="{ row }">
              <el-button type="primary" icon="user" @click="setRole(row)">
                分配角色
              </el-button>
              <el-button type="primary" icon="edit" @click="editUser(row)">
                编辑
              </el-button>
              <el-button type="primary" icon="delete" @click="delUser(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="common_pagination"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[30, 50, 100]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next, jumper,->,total, sizes"
          :total="total"
          @size-change="sizeChange"
          @current-change="getRoleList"
        />
      </el-card>
    </el-space>
    <!-- 添加角色 -->
    <Dialog
      :visible="diaologVisible"
      :dialogConfig="dialogConfig"
      @confirm="save"
      @close="closeDialog"
    >
      <template #content>
        <el-form :model="form" label-width="auto" :rules="rules" ref="roleForm">
          <el-form-item prop="roleName" label="角色名称">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
    <!-- 分配权限 -->
    <Drawer
      :visible="drawerRoleVisible"
      :title="drawerRoleTitle"
      :width="drawerRoleWidth"
      :modal="drawerRoleModal"
      @close="closeRoleDrawer"
    >
      <template #drawer-content>
        <el-tree
          ref="treeRef"
          node-key="id"
          show-checkbox
          v-loading="roleloading"
          element-loading-text="权限资源加载中..."
          :data="treeData"
          :props="defaultProps"
          :highlight-current="true"
          default-expand-all
          :expand-on-click-node="false"
          :default-checked-keys="menuIds"
          @check="handleCheckChange"
        />
      </template>
      <template #drawer-footer>
        <el-space wrap>
          <el-button type="primary" @click="saveRole" :loading="saveloading">
            保存
          </el-button>
          <el-button @click="closeRoleDrawer(false)">取消</el-button>
        </el-space>
      </template>
    </Drawer>
  </div>
</template>

<script setup lang="ts" name="Role">
import { ref, onMounted, nextTick } from 'vue'
import {
  reqRoleList,
  delRoleReq,
  addOrUpdateRoleReq,
  getRolePermissionReq,
  saveRolePermissionReq
} from '@/api/acl/role'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useLayoutStore } from '@/stores/modules/setting'
import '@/styles/common/index.less'

onMounted(() => {
  getRoleList()
})

let layoutStore = useLayoutStore()
let tableData = ref<any>([])
const currentPage = ref(1)
const pageSize = ref(30)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
let total = ref(0)
let loading = ref(false)
let keyword = ref('')
let diaologVisible = ref(false)
let dialogConfig = ref<any>({
  dialogTitle: '添加角色',
  dialogWidth: '550px',
  dialogShowClose: true,
  dialogModal: true,
  dialogAlignCenter: false,
  dialogContentCenter: false,
  dialogClickModalClose: false,
  dialogESCModalClose: false,
  dialogDraggable: false,
  dialogFooterBtn: true,
  dialogFootConfirmBtnText: '确定',
  dialogFootCancelBtnText: '取消'
})
let drawerRoleVisible = ref(false)
let drawerRoleTitle = ref('分配菜单与按钮权限')
let drawerRoleWidth = ref(800)
let drawerRoleModal = ref(true)
const form: any = ref({
  roleName: ''
})
const rules = {
  roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
}
// 获取 form 实例
const roleForm = ref()
let isAdd = ref(true)
let roleId = ref('')
let saveloading = ref(false)
const treeRef = ref()
let treeData = ref<any>([])
let roleloading = ref(true)
let menuIds = ref<any>([])
let defaultProps = ref<any>({
  children: 'children',
  label: 'name'
})

// 获取列表数据
const getRoleList = async (pager = 1) => {
  currentPage.value = pager
  loading.value = true
  let res: any = await reqRoleList(
    currentPage.value,
    pageSize.value,
    keyword.value
  )
  if (res.code === 200) {
    tableData.value = res.data.records
    total.value = res.data.total
    loading.value = false
  } else {
    ElMessage.error(res.message)
    loading.value = false
  }
}

// 分页器 自定义条数方法
const sizeChange = () => {
  getRoleList()
}

// 搜索
const searchUser = () => {
  getRoleList()
}

// 重置
const resetSearch = () => {
  layoutStore.refresh = !layoutStore.refresh
}

// 添加
const addUser = () => {
  diaologVisible.value = true
  isAdd.value = true
  form.value = {
    roleName: ''
  }
}

// 编辑
const editUser = (data: any) => {
  diaologVisible.value = true
  dialogConfig.value.dialogTitle = '编辑角色'
  isAdd.value = false
  Object.assign(form.value, data)
}

// 分配权限
const setRole = (data: any) => {
  drawerRoleVisible.value = true
  roleId.value = data.id
  getRolePermission(data.id)
}

// 单个删除方法
const delRoleMethod = async (id: any) => {
  let res: any = await delRoleReq(id)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getRoleList(
      tableData.value.length > 1 ? currentPage.value : currentPage.value - 1
    )
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 单个删除
const delUser = (data: any) => {
  ElMessageBox.confirm(`确定删除${data.roleName}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delRoleMethod(data.id)
  })
}

// 新增/编辑方法
const addOrUpdateRoleMethod = async (data: any) => {
  let res: any = await addOrUpdateRoleReq(data)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getRoleList(data.id ? currentPage.value : 1)
    closeDialog()
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
  saveloading.value = false
}

// 保存
const save = async () => {
  await roleForm.value.validate(async (valid: any) => {
    if (valid) {
      saveloading.value = true
      addOrUpdateRoleMethod(form.value)
    }
  })
}

// 关闭dialog
const closeDialog = () => {
  diaologVisible.value = false
  nextTick(() => {
    roleForm.value.resetFields()
  })
}

// 根据角色获取菜单
const getRolePermission = async (roleId: any) => {
  let res: any = await getRolePermissionReq(roleId)
  if (res.code === 200) {
    treeData.value = res.data
    menuIds.value = filterRolePermissionData(treeData.value, [])
    roleloading.value = false
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 过滤已选节点数据
const filterRolePermissionData = (treeData: any, initArr: any) => {
  treeData.forEach((item: any) => {
    if (item.level == 4 && item.select) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterRolePermissionData(item.children, initArr)
    }
  })
  return initArr
}

// node check
const handleCheckChange = (checkedNodes: any, nodeData: any) => {
  const { checkedKeys } = nodeData
  menuIds.value = checkedKeys
}

// 保存权限方法
const saveRolePermissionMethod = async (roleId: any, permissionId: any) => {
  let res: any = await saveRolePermissionReq(roleId, permissionId)
  if (res.code === 200) {
    ElMessage.success(res.message)
    closeRoleDrawer(false)
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
  saveloading.value = false
}

// 保存权限分配
const saveRole = async () => {
  saveloading.value = true
  saveRolePermissionMethod(roleId.value, menuIds.value)
}

// drawer role 回调
const closeRoleDrawer = (value: boolean) => {
  drawerRoleVisible.value = value
}
</script>

<style scoped>
.el-form-item__content {
  display: block;
}
</style>
